package com.bjb.vr.remote.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.alibaba.fastjson.JSONObject;
import com.bjb.vr.common.ao.ClientRequestAo;
import com.bjb.vr.common.constant.EncryptConstant;
import com.bjb.vr.common.constant.TokenConstants;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.result.BaseResult;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.BeanMapUtil;
import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.common.utils.JwtTokenUtil;
import com.bjb.vr.remote.properties.ServerInfoProperties;
import com.bjb.vr.remote.ws.rabbitmq.utils.AccessRequestUtil;
import com.bjb.vr.remote.ws.rabbitmq.utils.OkHttpUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * @description:
 * @author: caihaibo
 * @create: 2022-12-26 10:29
 **/
@Slf4j
@Service
public class HttpOperationService {

    @Resource
    private ServerInfoProperties serverInfoProperties;

    /**
     * 调用云端资源服务接口
     *
     * @param object
     * @return
     */
    public CommonResult postCloudApi(String authorization,Object object) {
        Map<String, Object> params = null;

        String postUrl = getRequestUrl();
        try {
            params = BeanMapUtil.beanToMap(object);
            generateSign(authorization,params);
            // 封装请求参数
            Iterator<Map.Entry<String, Object>> iterator = params.entrySet().stream().iterator();
            OkHttpUtil builder = OkHttpUtil.builder();
            builder.url(postUrl).addHeader(TokenConstants.AUTHORIZATION, authorization)
            .addHeader("Content-Type", "application/json; charset=utf-8");
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                builder.addParam(entry.getKey(), entry.getValue().toString());
            }
            // 解析响应体
            String response = builder.post(true).sync();
            JSONObject parseObject = JSONObject.parseObject(response);
            if (parseObject.get("success").equals(true)) {
                Object data = parseObject.get("data");
                return CommonResult.Ok().setResult(data);
            } else {
                Object message = parseObject.get("message");
                return CommonResult.Fail(message.toString());
            }
        } catch (Exception e) {
            throw new CommonException(e.getMessage());
        }
    }

    /**
     * 获取签名
     *
     * @return
     */
    private Map<String, Object> generateSign(String authorization,Map<String, Object> params) {
        CommonResult result = JwtTokenUtil.validateJWT(authorization);
        Claims claims = JwtTokenUtil.parseJWT(authorization);
        String tenantId = (String) claims.get(TokenConstants.TENANT_ID);

        StringBuilder builder = new StringBuilder();
        String requestId = UUID.fastUUID().toString();
        String requestTime = DateTimeUtil.nowStrTime();
        // 生成签名
        String data = builder.append(tenantId).append(requestId).append(requestTime).toString();
        byte[] key = EncryptConstant.ENCRYPT_KEY.getBytes();
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, key);
        String signature = mac.digestHex(data);
        // 保存数据
        params.put("tenantId", tenantId);
        params.put("requestId", requestId);
        params.put("requestTime", requestTime);
        params.put("signature", signature);
        return params;
    }

    /**
     * 获取请求地址
     *
     * @return
     */
    private String getRequestUrl() {
        String requestURI = AccessRequestUtil.getRequestURI().replace("remote", "operation").replace("v1", "v1/cloud").trim();
        return serverInfoProperties.getCloudServerUri() + requestURI;
    }


    /**
     * 获取眼镜云端课程资源列表接口
     *
     * @param resContentAo
     * @return
     */
    public BaseResult queryGlassResourcesList(String authorization,ClientRequestAo resContentAo) {
        return postCloudApi(authorization,resContentAo);
    }

}
